package com.sunlake.spring.main.model.orders.controller;

import com.sunlake.spring.main.common.response.R;
import com.sunlake.spring.main.model.orders.dto.OrdersCreateDTO;
import com.sunlake.spring.main.model.orders.dto.OrdersQueryDTO;
import com.sunlake.spring.main.model.orders.dto.PayOrderDTO;
import com.sunlake.spring.main.model.orders.service.OrdersService;
import com.sunlake.spring.main.common.utils.CurrentUserUtil;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

/**
 * �订单控制器
 * @author liuha
 */
@RestController
@RequestMapping("/api/orders")
public class OrdersController {
    @Autowired
    private OrdersService ordersService;

    @PostMapping
    public R createOrder(@Valid @RequestBody OrdersCreateDTO ordersCreateDTO, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return R.error(400, Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
        }
        Long userId = CurrentUserUtil.getCurrentUserId();
        if (userId == null) {
            return R.error(401, "请先登录");
        }
        return ordersService.createOrder(ordersCreateDTO, userId);
    }

    @PostMapping("/{orderNo}/pay")
    public R payOrder(@PathVariable String orderNo, @Valid @RequestBody PayOrderDTO payOrderDTO, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return R.error(400, Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
        }
        Long userId = CurrentUserUtil.getCurrentUserId();
        if (userId == null) {
            return R.error(401, "请先登录");
        }
        return ordersService.payOrder(orderNo, payOrderDTO, userId);
    }

    @GetMapping("/{orderNo}")
    public R getOrder(@PathVariable String orderNo) {
        return ordersService.getOrder(orderNo);
    }

    @GetMapping("/my")
    public R getMyOrders(@Valid OrdersQueryDTO queryDTO) {
        Long userId = CurrentUserUtil.getCurrentUserId();
        if (userId == null) {
            return R.error(401, "请先登录");
        }
        return ordersService.getMyOrders(queryDTO, userId);
    }

    @PutMapping("/{orderId}/cancel")
    public R cancelOrder(@PathVariable Long orderId) {
        // TODO: 实现取消订单逻辑
        return R.error(501, "功能暂未实现");
    }
}
